package com.lehecai.core.lottery.fetcher.dc.impl.worker;

import com.lehecai.core.lottery.fetcher.dc.AbstractSfggScheduleFetchWorker;
import com.lehecai.core.lottery.fetcher.dc.SfggScheduleItem;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreDateUtils;
import com.lehecai.core.util.CoreFetcherUtils;
import com.lehecai.core.util.CoreStringUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.CssSelectorNodeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CommonSfggScheduleFetchWorkerAIBO extends AbstractSfggScheduleFetchWorker {

	private static final String URL_AIBO = "http://trade.aibo123.com/dc_sfgg/";

	@SuppressWarnings("unchecked")
	@Override
	public List<SfggScheduleItem> fetch(String phase) {

        List<SfggScheduleItem> raceList = new ArrayList<SfggScheduleItem>();
        String data;
        Parser phaseParser;
        Parser parser;
        try {
            if (phase != null && !"".equals(phase)) {
                data = CoreFetcherUtils.URLGet(URL_AIBO + phase.substring(1) + "/", null, CharsetConstant.CHARSET_GBK);
            }else {
                data = CoreFetcherUtils.URLGet(URL_AIBO, null, CharsetConstant.CHARSET_GBK);
            }
        } catch (Exception e) {
            logger.error("获取html数据失败" + e.getMessage());
            return null;
        }
        if (data == null || "".equals(data)) {
            logger.error("胜负过关抓取赛程失败");
            return null;
        }
        try {
            phaseParser = Parser.createParser(data, CharsetConstant.CHARSET_GBK);
            parser = Parser.createParser(data, CharsetConstant.CHARSET_GBK);

        } catch (Exception e) {
            logger.error("解析html出错, data={}", data);
            return null;
        }
        try {
            //抓取彩期
            NodeList nodePhaseList;
            String phaseFromHtml;
            String tempPhase = "";
            try {
                nodePhaseList = phaseParser.extractAllNodesThatMatch(new CssSelectorNodeFilter("a[class='listbtn listhover']"));
                if (nodePhaseList.size() > 0) {
                    tempPhase = nodePhaseList.elementAt(0).toPlainTextString();
                }
            } catch (ParserException e) {
                logger.error("抓取彩期,解析html出错, nodePhaseList={}", e.getMessage());
                return null;
            }
            if ("".equals(tempPhase) || tempPhase.indexOf("第") < 0 || tempPhase.indexOf("期") < 0) {
                logger.error("胜负过关抓取赛程失败,未抓取到相应的彩期信息");
                return null;
            }
            phaseFromHtml = tempPhase.substring(tempPhase.indexOf("第") + 1, tempPhase.indexOf("期"));
            phaseFromHtml = (Calendar.getInstance().get(Calendar.YEAR) + "").substring(2, 3) + phaseFromHtml; //构造彩期
            //抓取赛程数据
            NodeList nodeList;
            NodeFilter tableFilter = new TagNameFilter("table");
            try {
                nodeList = parser.extractAllNodesThatMatch(tableFilter);
            } catch (ParserException e) {
                logger.error("抓取赛程数据,解析html出错, nodeList={}", e.getMessage());
                return null;
            }
            if (nodeList != null && nodeList.size() > 0) {
                TableTag catchTableTag = (TableTag)nodeList.elementAt(1);
                if (catchTableTag != null) {
                    TableRow[] catchRows = catchTableTag.getRows();
                    TableColumn[] catchColumns;
                    String date = "";
                    for (int i = 0; i < catchRows.length; i++) {
                        catchColumns = catchRows[i].getColumns();
                        //第一个tr  获取日期
                        if (catchColumns.length == 1) {
                            date = CoreStringUtils.trimAll(catchColumns[0].toPlainTextString());
                            if (!"".equals(date) && date.indexOf("星期") > 0) {
                                date = date.substring(0, date.indexOf("星期"));
                            }
                        }
                        //当前期  有比赛时间 和 销售截止时间
                        if (catchColumns != null && catchColumns.length == 12) {
                            SfggScheduleItem item = new SfggScheduleItem();
                            item.setPhase(phaseFromHtml);                                                                           //彩期
                            item.setMatchIndex(Integer.parseInt(CoreStringUtils.trimAll(catchColumns[0].toPlainTextString())));     //场次顺序
                            item.setLeague(CoreStringUtils.trimAll(catchColumns[1].toPlainTextString()));                           //联赛或赛事名称
                            NodeList columnsNoteList = catchColumns[2].getChildren();
                            if (columnsNoteList.size() == 5) {
                                item.setMatchDesc(CoreStringUtils.trimAll(columnsNoteList.elementAt(1).toPlainTextString()));                 //描述
                                item.setMatchRound(CoreStringUtils.trimAll(columnsNoteList.elementAt(3).toPlainTextString()));             //轮次
                            } else if (columnsNoteList.size() == 3) {
                                NodeList columnsNoteList1 = columnsNoteList.elementAt(1).getChildren();
                                if (columnsNoteList1 != null && columnsNoteList1.size() == 5) {
                                    item.setMatchDesc(CoreStringUtils.trimAll(columnsNoteList1.elementAt(1).toPlainTextString()));                 //描述
                                    item.setMatchRound(CoreStringUtils.trimAll(columnsNoteList1.elementAt(3).toPlainTextString()));             //轮次
                                }
                            } else {
                                logger.error("第" + CoreStringUtils.trimAll(catchColumns[0].toPlainTextString()) +"场次获取的赛程数据有问题");
                            }
                            NodeList homeTeamNoteList = catchColumns[5].getChildren();
                            if (homeTeamNoteList != null && homeTeamNoteList.size() >= 3) {
                                NodeList subHomeTeamNoteList = homeTeamNoteList.elementAt(1).getChildren();
                                if (subHomeTeamNoteList != null && subHomeTeamNoteList.size() > 8) {
                                    item.setHomeTeam(CoreStringUtils.trimAll(subHomeTeamNoteList.elementAt(8).toPlainTextString()));   //主队
                                }
                            }
                            NodeList awayTeamNoteList = catchColumns[7].getChildren();
                            if (awayTeamNoteList != null && awayTeamNoteList.size() >= 3) {
                                NodeList subWwayTeamNoteList = awayTeamNoteList.elementAt(1).getChildren();
                                if (subWwayTeamNoteList != null && subWwayTeamNoteList.size() > 8) {
                                    item.setAwayTeam(CoreStringUtils.trimAll(subWwayTeamNoteList.elementAt(8).toPlainTextString()));        //客队
                                }
                            }
                            item.setMatchTime(parseDate(date, CoreStringUtils.trimAll(catchColumns[3].toPlainTextString()), null));        //比赛时间
                            item.setEndSaleTime(parseDate(date, CoreStringUtils.trimAll(catchColumns[4].toPlainTextString()), item.getMatchTime()));        //销售截止时间
                            item.setHandicap(CoreStringUtils.trimAll(catchColumns[6].toPlainTextString()));                          //让球
                            raceList.add(item);
                        }
                        //非当前期  只有销售截止时间
                        if (catchColumns != null && catchColumns.length == 11) {
                            SfggScheduleItem item = new SfggScheduleItem();
                            item.setPhase(phaseFromHtml);                                                                           //彩期
                            item.setMatchIndex(Integer.parseInt(CoreStringUtils.trimAll(catchColumns[0].toPlainTextString())));     //场次顺序
                            item.setLeague(CoreStringUtils.trimAll(catchColumns[1].toPlainTextString()));                           //联赛或赛事名称
                            NodeList columnsNoteList = catchColumns[2].getChildren();
                            if (columnsNoteList.size() == 5 || columnsNoteList.size() == 7) {
                                item.setMatchDesc(CoreStringUtils.trimAll(columnsNoteList.elementAt(1).toPlainTextString()));                 //描述
                                item.setMatchRound(CoreStringUtils.trimAll(columnsNoteList.elementAt(3).toPlainTextString()));             //轮次
                            } else if (columnsNoteList.size() == 3) {                                                                      //特殊情况 数据来源没有的情况下
                                NodeList columnsNoteList1 = columnsNoteList.elementAt(1).getChildren();
                                if (columnsNoteList1 != null && columnsNoteList1.size() == 5) {
                                    item.setMatchDesc(CoreStringUtils.trimAll(columnsNoteList1.elementAt(1).toPlainTextString()));                 //描述
                                    item.setMatchRound(CoreStringUtils.trimAll(columnsNoteList1.elementAt(3).toPlainTextString()));             //轮次
                                }
                            } else {
                                logger.error("第" + CoreStringUtils.trimAll(catchColumns[0].toPlainTextString()) +"场次获取的赛程数据有问题");
                            }
                            NodeList homeTeamNoteList = catchColumns[4].getChildren();
                            if (homeTeamNoteList != null && homeTeamNoteList.size() >= 3) {
                                NodeList subHomeTeamNoteList = homeTeamNoteList.elementAt(1).getChildren();
                                if (subHomeTeamNoteList != null && subHomeTeamNoteList.size() > 8) {
                                    item.setHomeTeam(CoreStringUtils.trimAll(subHomeTeamNoteList.elementAt(6).toPlainTextString()));        //主队
                                }
                            }
                            NodeList awayTeamNoteList = catchColumns[6].getChildren();
                            if (awayTeamNoteList != null && awayTeamNoteList.size() >= 3) {
                                NodeList subWwayTeamNoteList = awayTeamNoteList.elementAt(1).getChildren();
                                if (subWwayTeamNoteList != null && subWwayTeamNoteList.size() > 8) {
                                    item.setAwayTeam(CoreStringUtils.trimAll(subWwayTeamNoteList.elementAt(2).toPlainTextString()));        //客队
                                }
                            }
                            item.setEndSaleTime(parseDate(date, CoreStringUtils.trimAll(catchColumns[3].toPlainTextString()), null));        //销售截止时间
                            item.setHandicap(CoreStringUtils.trimAll(catchColumns[5].toPlainTextString()));                          //让球
                            raceList.add(item);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("抓取赛程数据,解析html出错, e={}", e, e.getMessage());
            return null;
        }
		return raceList;
	}

    private Date parseDate (String inputDate, String inputTime, Date MatchTime) {
        Date date, pointDate;
        if (inputDate == null || "".equals(inputDate) || inputTime == null || "".equals(inputTime)) {
            return  null;
        }
        try {
            String [] array = inputDate.split("/");
            StringBuilder dateBuilder = new StringBuilder("");
            String dateStr = "";
            for (String string : array) {
                dateBuilder.append(string).append("-");
            }
            if (dateBuilder.lastIndexOf("-") > 0) {
                dateStr = dateBuilder.substring(0, dateBuilder.lastIndexOf("-"));
            }
            if (!"".equals(dateStr)) {
                date = CoreDateUtils.parseDate(dateStr + " " + inputTime + ": 00" ,CoreDateUtils.DATETIME);
                pointDate = CoreDateUtils.parseDate(dateStr + " 10:00:00" ,CoreDateUtils.DATETIME);               //开赛时间小于临界点的10:00:00 则设为第二天的比赛
                if (MatchTime != null && MatchTime.equals(pointDate)) {                                           //如果开赛时间刚好是10:00:00 这种情况，它的销售截止时间小于10:00:00 但不能设为第二天截止时间
                    logger.info("" + MatchTime);
                } else {
                    if (date.before(pointDate)) {
                        Calendar c=Calendar.getInstance();
                        c.setTime(date);
                        c.add(Calendar.DATE, 1);
                        date=c.getTime();
                    }
                }
                return date;
            }
        } catch (Exception e) {
            logger.error("抓取时间转换出错！" + e.getMessage());
        }
        return  null;
    }

	public static void main(String[] args) {
		AbstractSfggScheduleFetchWorker worker = new CommonSfggScheduleFetchWorkerAIBO();
		List<SfggScheduleItem> raceList = worker.fetch("140407");
		for (SfggScheduleItem item : raceList) {
			System.out.println(item.getSfggScheduleInfo());
		}
	}
}
